package io.github.shenbinglife.springboot2.layui.admin.dao;

import io.github.shenbinglife.springboot2.layui.admin.entity.Org;
import io.github.shenbinglife.springboot2.layui.admin.entity.OrgUserRelation;
import io.github.shenbinglife.springboot2.layui.admin.entity.User;
import io.github.shenbinglife.springboot2.layui.common.jpa.IBaseRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import java.util.List;

@Repository
public interface OrgDao extends IBaseRepository<Org, Long> {


    List<Org> findByParentIdOrderByOrdered(Long parentId);

    default void addUserToOrg(Long orgId, Long... userIds) {
        EntityManager em = getEm();
        for (Long userId : userIds) {
            em.persist(new OrgUserRelation(orgId, userId));
        }
    }

    @Query("select r from OrgUserRelation r where r.orgId=:orgId")
    List<OrgUserRelation> findUserRelationByOrgId(Long orgId);

    @Query("select r from OrgUserRelation r where r.userId=:userId")
    List<OrgUserRelation> findUserRelationByUserId(Long userId);

    @Modifying
    @Query("delete from OrgUserRelation r where r.userId=:userId")
    void removeRelationByUserId(Long userId);

    @Query("select o from Org o inner join OrgUserRelation r on r.orgId = o.id where" +
            " r.userId = :userId")
    List<Org> findOrgsByUserId(Long userId);

    @Modifying
    @Query("delete from OrgUserRelation r where r.orgId = :orgId and r.userId = :userId")
    void removeUserFromOrg(Long orgId, Long userId);

    @Query("select u from User u inner join OrgUserRelation r on r.userId=u.id" +
            " where r.orgId=:orgId")
    List<User> findUserByOrgId(Long orgId);

    @Query("select u from User u inner join OrgUserRelation r on u.id = r.userId where r.orgId=:orgId " +
            "and ( :keyword is NULL or :keyword = '' or u.name like CONCAT('%',:keyword,'%') or " +
            " u.account like CONCAT('%',:keyword,'%') )")
    Page<User> findUsersByOrgIdWithPagination(Long orgId, String keyword, Pageable pageRequest);

    @Modifying
    @Query("delete from OrgUserRelation r where r.orgId=:orgId")
    void removeRelationByOrgId(Long orgId);
}
